/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.Icon;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;

import ebml.ElementDescriptor;
import ebml.VInteger;
import ebml.viewer.tree.ExtendedTreeNode;
import ebml.viewer.tree.FormatTreeNode;
import ebml.viewer.tree.NodeIcons;
import ebml.viewer.tree.StringTreeNode;

/** Converts EBML content events into the <code>TreeModel</code>. */
public final class FileStructureTreeModelProvider implements FileTaskListener {

    private static final ResourceBundle RESOURCES = ResourceBundle.getBundle(Resources.class.getName());


    private static final MessageFormat waitingFormat = new MessageFormat(RESOURCES.getString("parsing.waiting"));

    private static final MessageFormat loadingFormat = new MessageFormat(RESOURCES.getString("parsing.loading"));

    private static final MessageFormat fileFormat = new MessageFormat(RESOURCES.getString("tree.structure.file"));

    private static final MessageFormat elementFormat = new MessageFormat(RESOURCES.getString("tree.structure.element"));

    private static final MessageFormat valueElementFormat = new MessageFormat(RESOURCES.getString("tree.structure.valueElement"));

    private static final MessageFormat unknownElementFormat = new MessageFormat(RESOURCES.getString("tree.structure.unknownElement"));

    private static final MessageFormat skippedElementFormat = new MessageFormat(RESOURCES.getString("tree.structure.skippedElement"));

    private static final MessageFormat exceptionFormat = new MessageFormat(RESOURCES.getString("tree.structure.exception"));


    private final DefaultTreeModel treeModel;

    private final FormatTreeNode messageNode;

    private final Deque<ExtendedTreeNode> nodeStack;

    private final Deque<List<TreeNode>> childrenStack;

    private final Deque<Boolean> loadContentsStack;

    private ExtendedTreeNode node;

    private List<TreeNode> children;

    private boolean loadContents;

    private long fileSize;

    private long fileProgress;

    private final ElementListTableModelProvider elementListTableModelProvider;


    /** Creates a new <code>FileStructureTreeModelProvider</code> object. */
    public FileStructureTreeModelProvider() {
        this(null);
    }

    /**
     * Creates a new <code>FileStructureTreeModelProvider</code> object.
     *
     * @param elementListTableModelProvider the known elements provider
     */
    public FileStructureTreeModelProvider(ElementListTableModelProvider elementListTableModelProvider) {
        this.elementListTableModelProvider = elementListTableModelProvider;
        messageNode = new FormatTreeNode(null, waitingFormat, null);
        treeModel = new DefaultTreeModel(messageNode, true);
        nodeStack = new LinkedList<ExtendedTreeNode>();
        childrenStack = new LinkedList<List<TreeNode>>();
        loadContentsStack = new LinkedList<Boolean>();
    }


    /**
     * Returns the <code>TreeModel</code> constructed by this provider.
     *
     * @return the tree model
     */
    public TreeModel getTreeModel() {
        return treeModel;
    }


    private void updateFileProgress(long filePosition) {
        long progress = filePosition * 100 / fileSize;
        if (progress > fileProgress) {
            fileProgress = progress;
            Number[] arguments = (Number[]) messageNode.getMessageArguments();
            arguments[0] = (double) filePosition / fileSize;
            nodeChanged(messageNode);
        }
    }

    private ExtendedTreeNode createElementNode(Icon icon, MessageFormat messageFormat, Object[] messageArguments) {
        // return new StringTreeNode(icon, messageFormat.format(messageArguments));
        return new FormatTreeNode(icon, messageFormat, messageArguments);
    }


    @Override
    public void startFile(File file, long size) {
        messageNode.setMessageFormat(loadingFormat);
        messageNode.setMessageArguments(new Number[1]);
        nodeChanged(messageNode);
        fileSize = size;
        nodeStack.clear();
        childrenStack.clear();
        loadContentsStack.clear();
        loadContents = true;
        node = new StringTreeNode(NodeIcons.FILE_ICON, fileFormat.format(new Object[] {file}));
        children = new ArrayList<TreeNode>();
    }

    @Override
    public void signedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.SIGNED_INTEGER_ICON, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void unsignedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.UNSIGNED_INTEGER_ICON, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void floatElement(long position, ElementDescriptor descriptor, VInteger size, Number value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.FLOAT_ICON, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void asciiStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.STRING_ICON, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void unicodeStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.STRING_ICON, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void dateElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(null, valueElementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
                    value,
            }));
        }
    }

    @Override
    public void binaryElement(long position, ElementDescriptor descriptor, VInteger size) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.BINARY_ICON, elementFormat, new Object[] {
                    Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                    descriptor.getName(),
                    descriptor.getType(),
                    size.getValue(),
            }));
        }
    }

    @Override
    public void startContainer(long position, ElementDescriptor descriptor, VInteger size) {
        updateFileProgress(position);
        boolean childLoadContents = loadContents
                && (elementListTableModelProvider == null || elementListTableModelProvider.isLoadContents(descriptor.getIdentifier()));
        ExtendedTreeNode child = createElementNode(NodeIcons.CONTAINER_ICON, childLoadContents ? elementFormat : skippedElementFormat, new Object[] {
                Long.toHexString(descriptor.getIdentifier().getEncodedValue()),
                descriptor.getName(),
                descriptor.getType(),
                size.getValue(),
        });
        if (loadContents) {
            children.add(child);
        }
        nodeStack.addFirst(node);
        childrenStack.addFirst(children);
        loadContentsStack.addFirst(loadContents);
        node = child;
        children = childLoadContents ? new ArrayList<TreeNode>() : Collections.<TreeNode>emptyList();
        loadContents = childLoadContents;
    }

    @Override
    public void endContainer(long position, ElementDescriptor descriptor) {
        updateFileProgress(position);
        if (loadContents) {
            node.setChildren(children.toArray(new TreeNode[children.size()]));
        }
        node = nodeStack.removeFirst();
        children = childrenStack.removeFirst();
        loadContents = loadContentsStack.removeFirst();
    }

    @Override
    public void unknownElement(long position, VInteger identifier, VInteger size) {
        updateFileProgress(position);
        if (loadContents) {
            children.add(createElementNode(NodeIcons.UNKNOWN_ICON, unknownElementFormat, new Object[] {
                    Long.toHexString(identifier.getEncodedValue()),
                    size.getValue()
            }));
        }
    }

    @Override
    public void endFile() {
        if (nodeStack.isEmpty()) {
            node.setChildren(children.toArray(new TreeNode[children.size()]));
            setRoot(node);
        } else {
            throw new AssertionError();
        }
    }

    @Override
    public void error(Throwable e) {
        while (!nodeStack.isEmpty()) {
            endContainer(-1, null);
        }
        children.add(new StringTreeNode(NodeIcons.EXCEPTION_ICON, exceptionFormat.format(new Object[] {e})));
    }

    @Override
    public void fatalError(Throwable e) {
        node = nodeStack.removeLast();
        nodeStack.clear();
        childrenStack.clear();
        children.clear();
        children.add(new StringTreeNode(NodeIcons.EXCEPTION_ICON, exceptionFormat.format(new Object[] {e})));
    }


    private void setRoot(final TreeNode treeNode) {
        if (SwingUtilities.isEventDispatchThread()) {
            setRootUnsafe(treeNode);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setRootUnsafe(treeNode);
                }
            });
        }
    }

    private void setRootUnsafe(TreeNode treeNode) {
        treeModel.setRoot(treeNode);
    }

    private void nodeChanged(final TreeNode treeNode) {
        if (SwingUtilities.isEventDispatchThread()) {
            nodeChangedUnsafe(treeNode);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    nodeChangedUnsafe(treeNode);
                }
            });
        }
    }

    private void nodeChangedUnsafe(TreeNode treeNode) {
        treeModel.nodeChanged(treeNode);
    }

}
